﻿CREATE PROCEDURE [Auth].[CreateNewAccount]
  @FirstName NVARCHAR(30),
  @LastName NVARCHAR(30),
  @DisplayName NVARCHAR(255) = NULL,
  @Password NVARCHAR(255) = NULL,
  @EmailAddress NVARCHAR(255),
  @AuthenticationSignInName NVARCHAR(255) = NULL,
  @AuthenticationTypeID SMALLINT,
  @AccountID INT OUTPUT
WITH EXECUTE AS OWNER
AS
SET NOCOUNT ON;
BEGIN TRY
  BEGIN TRANSACTION
  
  IF @DisplayName IS NULL
    SET @DisplayName = @FirstName + ' ' + @LastName;
  
  IF @AuthenticationSignInName IS NULL
    SET @AuthenticationSignInName = @EmailAddress;
  
  INSERT INTO Auth.Accounts
  (
    FirstName,
    LastName,
    DisplayName,
    Password,
    EmailAddress,
    AuthenticationSignInName,
    AuthenticationTypeId
  )
  VALUES
  (
    @FirstName,
    @LastName,
    @DisplayName,
    @Password,
    @EmailAddress,
    @AuthenticationSignInName,
    @AuthenticationTypeID
  )
  
  SET @AccountID = SCOPE_IDENTITY();
  
  COMMIT TRANSACTION
END TRY
BEGIN CATCH
  SET @AccountID = -1;
  
  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
  
  DECLARE @ERROR_SEVERITY AS INT,
    @ERROR_STATE AS INT,
    @ERROR_NUMBER AS INT,
    @ERROR_LINE AS INT,
    @ERROR_MESSAGE AS NVARCHAR(4000);

  SELECT
    @ERROR_SEVERITY = ERROR_SEVERITY(),
    @ERROR_STATE = ERROR_STATE(),
    @ERROR_NUMBER = ERROR_NUMBER(),
    @ERROR_LINE = ERROR_LINE(),
    @ERROR_MESSAGE = ERROR_MESSAGE();

  RAISERROR('Msg %d, Line %d, :%s',
    @ERROR_SEVERITY,
    @ERROR_STATE,
    @ERROR_NUMBER,
    @ERROR_LINE,
    @ERROR_MESSAGE);

END CATCH